define([ "jquery", "core" ], function($, core) {
	 window.initdialogtreedata={};
	 window.initdialogtreeparam={};
	
	_loadData = function(id, param) {// 更新一棵树
		var url = $('#' + id + '_treeLoadUrl').val();
		if (!url) {
			core.alert('没有设置加载地址');
			return;
		}
		$.post(core.packurl(url), param, function(data) {
			$('#' + id + '_tree').tree('loadData', data);
			var treename=id + '_tree';
			window.initdialogtreedata[treename]=$('#' + id + '_tree').tree('getChecked');
			window.initdialogtreeparam[treename]=param;
			core.opendialog2(id + '_dialog'); 
		}, 'json');
	}
	
	_selectall=function(id){//全选
		var nodes = $('#' + id + '_tree').tree('getChecked', 'unchecked');
		 $.each(nodes,function(i,n){
			 $('#' + id + '_tree').tree('check',n.target);			  
	 	 });
	}
	_selectno=function(id){//全不选
		var nodes =$('#' + id + '_tree').tree('getChecked');
		 $.each(nodes,function(i,n){
			 $('#' + id + '_tree').tree('uncheck',n.target);			  
	 	 });
	}
	_selectinit=function(id){
		var treename=id + '_tree';
		_selectno(id);
		 $.each(window.initdialogtreedata[treename],function(i,n){
			 $('#' + id + '_tree').tree('check',n.target);				  
	 	 });		
	}
	_save=function(url,id,sucHandle,checkHandle){//保存选择的值
		
		//var checkHandleFun=  new Function('return '+checkHandle)();
		//现在选择的ids
		var ids=[];
		var sels=$('#' + id + '_tree').tree('getChecked');	
		 $.each(sels,function(i,n){
			 ids.push(n.id);			  
	 	 });
		ids.sort();
		
		if(checkHandle!=null&& checkHandle!=''){
		    var checkHandleFun=  new Function('return '+checkHandle)();
		    if(!checkHandleFun(ids)){
		      $.messager.progress('close');
				return;
		     }			 
		}
		
		//得到原来选择的ids
		var treename=id + '_tree';
		var idsold=[];
		var selsold=window.initdialogtreedata[treename];
		 $.each(selsold,function(i,n){
			 idsold.push(n.id);			  
	 	 });
		 idsold.sort();
		 //比较选择的ids有没有改变
		 if(ids.length==idsold.length){
			 var issame=true;
			 $.each(ids,function(i,n){
				if($.inArray(n,idsold)<0){
					issame=false;
					return false;
				}			  
		 	 }); 
			 if(issame){//没有元素修改
				 core.alert('没有选项修改，无需提交.');
				 $.messager.progress('close');
				 return;
			 }
		 }
		 
		
		ids=JSON.stringify(ids);		
		var params=window.initdialogtreeparam[treename];
		$.post(url,{'ids':ids,'params':JSON.stringify(params)},function(data){
			core.opt2(data,function(){
				if(sucHandle!=null&& sucHandle!=''){
					var sucHandleFun=  new Function('return '+sucHandle)();
					sucHandleFun(data);
				}else{
					core.alert(data.msg);
				}
			});
			$.messager.progress('close');
		},'json');		
	};

	return {
		loadData : _loadData,selectall:_selectall,selectno:_selectno,selectinit:_selectinit,save:_save
	};
});